package wxminipro

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/pkg/errors"
)

type LoginResult struct {
	Openid     string          `json:"openid"`
	SessionKey string          `json:"session_key"`
	Unionid    string          `json:"unionid"`
	Errcode    LoginResultCode `json:"errcode"`
	Errmsg     string          `json:"errmsg"`
}

type LoginResultCode int

const (
	LoginResultCodeBusy    LoginResultCode = -1    // 系统繁忙，此时请开发者稍候再试
	LoginResultCodeSuccess LoginResultCode = 0     // 请求成功
	LoginResultCodeInValid LoginResultCode = 40029 // code 无效
	LoginResultCodeLimit   LoginResultCode = 45011 //  频率限制，每个用户每分钟100次
)

func Login(code string) (result *LoginResult, err error) {
	appId := beego.AppConfig.String("appId")
	secret := beego.AppConfig.String("appSecret")
	if appId == "" {
		err = errors.New("appId can not be empty")
		return
	}
	if secret == "" {
		err = errors.New("secret can not be empty")
		return
	}
	// GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	req := httplib.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, secret, code))
	result = &LoginResult{}
	err = req.ToJSON(result)
	if err != nil {
		return
	}
	return
}
